package com.kzd.gtboon.main.game

import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.BarUtils
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player.REPEAT_MODE_ALL
import com.google.android.exoplayer2.SimpleExoPlayer
import com.kzd.gtboon.R
import com.kzd.gtboon.callback.AppPagerAdapter
import com.kzd.gtboon.custom.setOnClickAntiShakeListener
import com.kzd.gtboon.custom.setTransitionStatus
import com.kzd.gtboon.databinding.ActivityGameDetailsBinding
import com.kzd.gtboon.entity.GameDetails
import com.kzd.gtboon.jetpack.vm.GameViewModel
import com.kzd.gtboon.main.*
import com.kzd.gtboon.main.game.adapter.GameListLabelAdapter
import com.kzd.gtboon.main.popup.GameExchangePopup
import com.module.lemlin.http.Status
import com.module.lemlin.image.loadImage
import com.module.lemlin.owner.OwnerViewBindingActivity
import com.module.lemlin.owner.ownerViewModel
import java.lang.Exception


class GameDetailsActivity : OwnerViewBindingActivity<ActivityGameDetailsBinding>() {

    companion object {
        private val tabs = arrayOf("详情", "福利", "开服")
    }

    private val mAppPagerAdapter: AppPagerAdapter by lazy {
        object : AppPagerAdapter(supportFragmentManager, tabs) {

            private val fragments = mutableListOf(
                GameDetailsFragment.newInstance(),
                GameWelfareFragment.newInstance(),
                GameServiceFragment.newInstance()
            )

            override fun fragment(position: Int): Fragment = fragments[position]
        }
    }

    private val mGameExchangePopup: GameExchangePopup by lazy {
        GameExchangePopup(context = this)
    }

    private val mGameId: String
        get() = intent.extras?.getString(KEY_GAME_DETAILS_ID) ?: ""

    private val mAction: Int
        get() = try {
            (intent.extras?.getString(KEY_GAME_DETAILS_INDEX) ?: "0").toInt()
        } catch (e: Exception) {
            0
        }

    private var mSimpleExoPlayer: SimpleExoPlayer? = null

    private val mViewModel: GameViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater) -> ActivityGameDetailsBinding
        get() = ActivityGameDetailsBinding::inflate

    override fun initView() {

        BarUtils.addMarginTopEqualStatusBarHeight(mViewBinding.tbGameDetailsBar)

        mViewBinding.ivGameDetailsBack.setOnClickListener {
            finish()
        }

        mViewBinding.tabGameDetailsKind.apply {
            for (item in tabs) {
                addTab(newTab().setText(item))
            }
        }.setupWithViewPager(mViewBinding.vpGameDetailsBody.apply {
            adapter = mAppPagerAdapter
        })

        mViewBinding.tabGameDetailsKind.getTabAt(mAction)?.select()

        mViewBinding.pvGameDetailsPlayer.findViewById<CheckBox>(R.id.exo_volume)
            .setOnCheckedChangeListener { _, isChecked ->
                mSimpleExoPlayer?.volume = if (isChecked) 1f else 0f
            }

        //联系客服
        mViewBinding.tvGameDetailsConnectService.setOnClickAntiShakeListener {
            toServiceMessageActivity()
        }

        //获取兑换码
        mViewBinding.tvGameDetailsExchangeCode.setOnClickAntiShakeListener {
            checkLogin {
                mViewModel.gameExchangeCode(mGameId)
            }
        }
    }

    override fun initData() {
        mViewModel.gameDetails(gid = mGameId)
        mViewModel.userService()
    }

    override fun initViewMode() {
        mViewModel.gameDetailsLiveData.observe(this as LifecycleOwner, { response ->
            mViewBinding.mslMultiStateLayout.setLoadingStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            val gameDetails: GameDetails = response.data?.data
                ?: return@observe
            fillData(gameDetails)
        })
        mViewModel.gameExchangeCodeLiveData.observe(this as LifecycleOwner, { response ->
            setTransitionStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val gameName = mViewModel.gameDetailsLiveData.value?.data?.data?.name ?: ""
            mGameExchangePopup.fillData(gameName, data)
                .showPopupWindow()
        })
    }

    override fun onResume() {
        super.onResume()
        if (mSimpleExoPlayer?.isPlaying != true) {
            mSimpleExoPlayer?.play()
        }
    }

    override fun onPause() {
        super.onPause()
        mSimpleExoPlayer?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mSimpleExoPlayer?.release()
    }

    private fun fillData(gd: GameDetails) {
        mViewBinding.ivGameDetailsImage.loadImage(
            src = gd.image ?: R.mipmap.ic_80003,
            R.mipmap.ic_80003,
            R.mipmap.ic_80003
        )

        mViewBinding.ivGameDetailsImage.visibility = if (gd.video.isNullOrEmpty())
            View.VISIBLE else View.GONE
        if (!gd.video.isNullOrEmpty()) {
            if (mSimpleExoPlayer == null) {
                mSimpleExoPlayer = SimpleExoPlayer.Builder(this).build()
                mSimpleExoPlayer?.repeatMode = REPEAT_MODE_ALL
                mSimpleExoPlayer?.volume = 0f
                mViewBinding.pvGameDetailsPlayer.player = mSimpleExoPlayer
            }
            val uri = Uri.parse(gd.video)
            val mediaItem: MediaItem = MediaItem.fromUri(uri)
            mSimpleExoPlayer?.setMediaItem(mediaItem)
            mSimpleExoPlayer?.prepare()
            mSimpleExoPlayer?.play()
        }

        mViewBinding.includeGameDetails1.ivGame1Icon.loadImage(
            src = gd.icon ?: R.mipmap.ic_80008,
            R.mipmap.ic_80008,
            R.mipmap.ic_80008
        )
        mViewBinding.includeGameDetails1.tvGame1Name.text = gd.name
        mViewBinding.includeGameDetails1.tvGame1Type.text = StringBuilder().append(gd.type)
            .append("\t·\t").append(gd.number).append("次下载")
        mViewBinding.includeGameDetails1.rvGame1LabelBody.apply {
            val layoutManager = LinearLayoutManager(context).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
            this.layoutManager = layoutManager
        }.adapter = GameListLabelAdapter().apply {
            setNewInstance(gd.biaoqian.toMutableList())
        }
    }
}